package com.ruoyi.project.system.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.github.binarywang.wxpay.bean.order.WxPayAppOrderResult;
import com.github.binarywang.wxpay.bean.request.WxPayRefundRequest;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.bean.result.WxPayRefundResult;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.exception.CustomException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ToolUtil;
import com.ruoyi.common.utils.pay.AlipayConfig;
import com.ruoyi.framework.redis.RedisCache;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.system.domain.*;
import com.ruoyi.project.system.mapper.SysUserMoneyMapper;
import com.ruoyi.project.system.service.ISysConfigService;
import com.ruoyi.project.system.service.ISysGoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.ruoyi.project.system.mapper.SysGoodsOrderMapper;
import com.ruoyi.project.system.service.ISysGoodsOrderService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import test.util.SequenceUtils;

/**
 * 二手物品订单Service业务层处理
 *
 * @author jjp
 * @date 2020-04-24
 */
@Service
public class SysGoodsOrderServiceImpl implements ISysGoodsOrderService {
    @Autowired
    private SysGoodsOrderMapper sysGoodsOrderMapper;

    @Autowired
    private SysUserMoneyMapper sysUserMoneyMapper;

    @Autowired
    private ISysGoodsService sysGoodsService;

    @Autowired
    public RedisTemplate redisTemplate;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private WxPayService wxPayService;

    @Autowired
    private ISysConfigService configService;


    //定时7天收货
    @Override
    public void confirmService() {
        List<SysGoodsOrder> sysGoodsOrders = sysGoodsOrderMapper.confirmOrderList();
        System.out.println("+_+_+_+_+_+_+_+" + sysGoodsOrders.size());
        if (!sysGoodsOrders.isEmpty()) {
            for (int i = 0; i < sysGoodsOrders.size(); i++) {
                SysGoodsOrder sysGoodsOrder = sysGoodsOrders.get(i);
                sysGoodsOrder.setGoodsOrderStatus("5");
                int i1 = sysGoodsOrderMapper.updateSysGoodsOrder(sysGoodsOrder);
                if (i1 == 1) {
                    //新增明细
                    SysUserMoney sysUserMoney = new SysUserMoney();
                    sysUserMoney.setMobileUserId(sysGoodsOrder.getMobileUserId());
                    sysUserMoney.setGoodsOrderId(sysGoodsOrder.getGoodsOrderId());
                    sysUserMoney.setMoney(sysGoodsOrder.getMoney());
                    sysUserMoney.setMoneyType("2");
                    sysUserMoneyMapper.insertSysUserMoney(sysUserMoney);
                }
            }
        }
    }

    /**
     * 查询二手物品订单
     *
     * @param goodsOrderId 二手物品订单ID
     * @return 二手物品订单
     */
    @Override
    public SysGoodsOrder selectSysGoodsOrderById(Long goodsOrderId) {
        return sysGoodsOrderMapper.selectSysGoodsOrderById(goodsOrderId);
    }

    @Override
    public SysGoodsOrder selectSysGoodsOrderByNo(String orderNo) {
        return sysGoodsOrderMapper.selectSysGoodsOrderByNo(orderNo);
    }

    /**
     * 查询二手物品订单列表
     *
     * @param sysGoodsOrder 二手物品订单
     * @return 二手物品订单
     */
    @Override
    public List<SysGoodsOrder> selectSysGoodsOrderList(SysGoodsOrder sysGoodsOrder) {
        return sysGoodsOrderMapper.selectSysGoodsOrderList(sysGoodsOrder);
    }

    /**
     * 新增二手物品订单
     *
     * @param sysGoodsOrder 二手物品订单
     * @return 结果
     */
    @Override
    public int insertSysGoodsOrder(SysGoodsOrder sysGoodsOrder) {
        sysGoodsOrder.setCreateTime(DateUtils.getNowDate());
        return sysGoodsOrderMapper.insertSysGoodsOrder(sysGoodsOrder);
    }

    @Override
    public AjaxResult createGoodsOrderService(SysGoodsOrder sysGoodsOrder) {
        if (null == sysGoodsOrder) {
            return AjaxResult.error("参数错误");
        }
        if (null == sysGoodsOrder.getGoodsId()) {
            return AjaxResult.error("二手商品id未传");
        }
        if (null == sysGoodsOrder.getAddressId()) {
            return AjaxResult.error("未选择地址");
        }
        if (null == sysGoodsOrder.getMoney()) {
            return AjaxResult.error("价格为空");
        }
        SysGoods goods = sysGoodsService.selectSysGoodsById(sysGoodsOrder.getGoodsId());
        if (null == goods) {
            return AjaxResult.error("商品异常");
        }
        if (!(goods.getMoney() + "").equals(sysGoodsOrder.getMoney() + "")) {
            return AjaxResult.error("订单价格和商品价格不一致");
        }
        if ("2".equals(goods.getItemStatus())) {
            return AjaxResult.error("商品已被其它用户下单");
        }
        if (!"1".equals(goods.getItemStatus())) {
            return AjaxResult.error("商品状态异常");
        }
        //** 获取今天的日期:yyyyMMdd *//*
        String date = SequenceUtils.getCurentDate();
        String key = "serial.gooods:" + date;
        //** 自增 *//*
        long sequence = redisTemplate.opsForValue().increment(key);
        String orderCode = date + SequenceUtils.getSequence(sequence);
        sysGoodsOrder.setOrderNo("G" + orderCode);
        sysGoodsOrder.setMobileUserId(SecurityUtils.getLoginUser().getSysMobileUser().getMobileUserId());
        sysGoodsOrder.setPayStatus("0");
        sysGoodsOrder.setGoodsOrderStatus("0");
        sysGoodsOrder.setCreateBy(SecurityUtils.getLoginUser().getSysMobileUser().getUserName());
        sysGoodsOrder.setCreateTime(new Date());
        int flag = sysGoodsOrderMapper.insertSysGoodsOrder(sysGoodsOrder);
        goods.setItemStatus("2");
        sysGoodsService.updateSysGoods(goods);
        /**
         * 设置服务订单超时时间
         */
        Object value = configService.selectConfigByKey("CONFIG_GOODS_ORDER");
        redisCache.setCacheObject(sysGoodsOrder.getOrderNo(), sysGoodsOrder.getOrderNo(), Integer.valueOf(value + ""), TimeUnit.MINUTES);
        if (flag == 1) {
            return AjaxResult.success("创建成功", sysGoodsOrder.getGoodsOrderId());
        }
        return AjaxResult.error("生成二手物品订单错误!");
    }

    @Override
    public List<SysGoodsOrder> getMyGoods(SysGoodsOrder sysGoodsOrder) {
        return sysGoodsOrderMapper.getMyGoods(sysGoodsOrder);
    }

    @Override
    public AjaxResult payGoodsOrderService(SysGoodsOrder sysGoodsOrder) {

        if (null == sysGoodsOrder) {
            return AjaxResult.error("参数错误");
        }
        if (null == sysGoodsOrder.getGoodsOrderId()) {
            return AjaxResult.error("订单id必传");
        }
        if (null == sysGoodsOrder.getPayType()) {
            return AjaxResult.error("支付方式必传");
        }
        SysGoodsOrder order = sysGoodsOrderMapper.selectSysGoodsOrderById(sysGoodsOrder.getGoodsOrderId());
        if (null == order) {
            return AjaxResult.error("订单id错误");
        }
        if (!order.getGoodsOrderStatus().equals("0")) {
            return AjaxResult.error("订单状态错误");
        }
        if (null == order.getMoney()) {
            return AjaxResult.error("订单金额错误");
        }
        Double money = order.getMoney();
        String title = "蚂蚁生活服务订单";
        //支付宝
        if (sysGoodsOrder.getPayType().equals("1")) {
            // SDK 公共请求类，包含公共请求参数，以及封装了签名与验签，开发者无需关注签名与验签
            //调用RSA签名方式，这个不用你管，只要你配置文件是正确的
            AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL,
                    AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT,
                    AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.SIGNTYPE);
            AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
            AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
            model.setSubject(title);//标题
            model.setOutTradeNo(order.getOrderNo());//商家唯一订单号
            model.setTimeoutExpress("15m");//1分钟没有支付，交易将会关闭
            model.setTotalAmount(money + "");//订单总额
            request.setBizModel(model);
            try {
                AlipayTradeAppPayResponse response = client.sdkExecute(request);
                System.out.println(JSONObject.toJSONString(response));
                if (response.isSuccess()) {
                    return AjaxResult.success(null, response.getBody());
                }
            } catch (AlipayApiException e) {
                e.printStackTrace();
            }
        } else if (sysGoodsOrder.getPayType().equals("2")) {
            //微信支付
            BigDecimal bg = new BigDecimal(money * 100);
            double doubleValue = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
            WxPayUnifiedOrderRequest.WxPayUnifiedOrderRequestBuilder builder = WxPayUnifiedOrderRequest.newBuilder();
            WxPayUnifiedOrderRequest request = builder.body(title)
                    .totalFee((int) doubleValue).outTradeNo(order.getOrderNo())
                    .spbillCreateIp("0.0.0.0")
                    .tradeType("APP").build();
            WxPayAppOrderResult o = null;
            try {
                o = wxPayService.createOrder(request);
            } catch (WxPayException e) {
                throw new BaseException("微信支付报错");
            }
            return AjaxResult.success(o);
        }
        return AjaxResult.error("支付失败");
    }

    @Override
    @Transactional
    public Boolean alipayBack(String orderNo, String payType, String totalMoney) {
        SysGoodsOrder sysGoodsOrder = sysGoodsOrderMapper.selectSysGoodsOrderByNo(orderNo);
        if (null == sysGoodsOrder) {
            return false;
        }
        if (new BigDecimal(totalMoney).compareTo(new BigDecimal(sysGoodsOrder.getMoney() + "")) != 0) {
            //订单金额错误
            return false;
        }
        if ("0".equals(sysGoodsOrder.getGoodsOrderStatus()) && "0".equals(sysGoodsOrder.getPayStatus())) {
            sysGoodsOrder.setPayStatus("2");
            sysGoodsOrder.setGoodsOrderStatus("3");
            sysGoodsOrder.setPayType(payType);
            sysGoodsOrder.setPayTime(new Date());
            int flag = sysGoodsOrderMapper.updateSysGoodsOrder(sysGoodsOrder);
            if (flag > 0) {
                SysGoods sysGoods = sysGoodsService.selectSysGoodsById(sysGoodsOrder.getGoodsId());
                sysGoods.setItemStatus("3");
                flag = sysGoodsService.updateSysGoods(sysGoods);
                if (flag > 0) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 修改二手物品订单
     *
     * @param sysGoodsOrder 二手物品订单
     * @return 结果
     */
    @Override
    public int updateSysGoodsOrder(SysGoodsOrder sysGoodsOrder) {
        sysGoodsOrder.setUpdateTime(DateUtils.getNowDate());
        return sysGoodsOrderMapper.updateSysGoodsOrder(sysGoodsOrder);
    }

    @Override
    @Transactional
    public AjaxResult sendGoods(SysGoodsOrder sysGoodsOrder) {
        SysGoodsOrder order = sysGoodsOrderMapper.selectSysGoodsOrderById(sysGoodsOrder.getGoodsOrderId());
        if (sysGoodsOrder.getExpressNo().isEmpty()) {
            return AjaxResult.error("快递单号不能为空");
        }
        if (null == order) {
            return AjaxResult.error("订单id错误");
        }
        order.setExpressNo(sysGoodsOrder.getExpressNo());
        order.setExpressTime(new Date());
        order.setOrderStatus("1");
        order.setGoodsOrderStatus("4");
        int flag = sysGoodsOrderMapper.updateSysGoodsOrder(order);
        if (flag > 0) {
            return AjaxResult.success("发货成功!");
        }
        return AjaxResult.error("系统错误!");
    }

    @Override
    public AjaxResult auditGoods(SysGoodsOrder sysGoodsOrder) {
        if(null==sysGoodsOrder.getGoodsOrderId()){
            return AjaxResult.error("订单id必传!");
        }
        SysGoodsOrder order=sysGoodsOrderMapper.selectSysGoodsOrderById(sysGoodsOrder.getGoodsOrderId());
        if(!"0".equals(order.getCancelStatus())){
            return AjaxResult.error("订单状态错误");
        }
        if("1".equals(sysGoodsOrder.getCancelStatus())){
            //审核同意退款
            if("1".equals(sysGoodsOrder.getPayType())){
                //支付方式为支付宝
                AlipayTradeRefundResponse response = null;
                AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL,
                        AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT,
                        AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE);
                AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
                request.setBizContent("{"+
                        "\"out_trade_no\":\""+order.getOrderNo()+"\"," +
                        "\"refund_amount\":"+order.getMoney()+"," +
                        "\"out_request_no\":\""+order.getOrderNo()+"\"" +
                        "  }");
                try {
                    response = alipayClient.execute(request);
                } catch (AlipayApiException e) {
                    e.printStackTrace();
                }
                if(response == null){
                    return AjaxResult.error("支付宝退款错误！");
                }
                if(response.isSuccess()){
                    order.setCancelStatus("1");
                    order.setOrderStatus("6");
                    sysGoodsOrderMapper.updateSysGoodsOrder(order);
                    return AjaxResult.success("退款成功!");
                }
            }
            if("2".equals(order.getPayType())){
                //支付方式为微信
                WxPayRefundResult result = null;
                WxPayRefundRequest wxPayRefundRequest=new WxPayRefundRequest();
                wxPayRefundRequest.setOutTradeNo(order.getOrderNo());
                wxPayRefundRequest.setOutRefundNo(order.getOrderNo());
                wxPayRefundRequest.setTotalFee(ToolUtil.yuanToFen(order.getMoney()+""));
                wxPayRefundRequest.setRefundFee(ToolUtil.yuanToFen(order.getMoney()+""));
                try {
                    result=wxPayService.refund(wxPayRefundRequest);
                } catch (WxPayException e) {
                    e.printStackTrace();
                    throw new CustomException("微信退款错误!");
                }
                if(result == null){
                    throw new CustomException("微信退款错误!");
                }
                if("SUCCESS".equals(result.getReturnCode())){
                    order.setCancelStatus("1");
                    order.setOrderStatus("6");
                    sysGoodsOrderMapper.updateSysGoodsOrder(order);
                    return AjaxResult.success("退款成功!");
                }
            }
        }else if("2".equals(sysGoodsOrder.getCancelStatus())){
            //审核不同意退款
            order.setCancelStatus("2");
            sysGoodsOrderMapper.updateSysGoodsOrder(order);
            return AjaxResult.success("审核成功!");
        }

        return null;
    }

    /**
     * 批量删除二手物品订单
     *
     * @param goodsOrderIds 需要删除的二手物品订单ID
     * @return 结果
     */
    @Override
    public int deleteSysGoodsOrderByIds(Long[] goodsOrderIds) {
        return sysGoodsOrderMapper.deleteSysGoodsOrderByIds(goodsOrderIds);
    }

    /**
     * 删除二手物品订单信息
     *
     * @param goodsOrderId 二手物品订单ID
     * @return 结果
     */
    @Override
    public int deleteSysGoodsOrderById(Long goodsOrderId) {
        return sysGoodsOrderMapper.deleteSysGoodsOrderById(goodsOrderId);
    }
}
